// 登录组件
import { useEffect, useState } from 'react';
import {
  Button,
  Form,
  Input,
  message
} from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import './login.less';
// import logo from "src/assets/images/logo.png";
import logo from '../../assets/images/logo.png'
import { reqLogin } from '../../api';
import storageUtils from '../../utils/storageUtils';
import memoryUtils from '../../utils/memoryUtils';

const Login = () => {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(true);
  const storedUser = storageUtils.getUser();

  useEffect(() => {
    const checkLoginStatus = () => {
      if (memoryUtils.user?._id || storedUser?._id) {
        if (storedUser) {
          memoryUtils.user = storedUser;
        }
        navigate('/admin', { replace: true });
      }
      setIsLoading(false);
    };
    checkLoginStatus();
  }, [navigate, storedUser]);

  if (isLoading) {
    return null;
  }

  const validateUsername = (rule, value) => {
    if (!value) return Promise.reject('用户名必须输入');
    if (value.length < 4) return Promise.reject('用户名至少4位');
    if (value.length > 12) return Promise.reject('用户名最多12位');
    if (!/^[a-zA-Z0-9_]+$/.test(value))
      return Promise.reject('用户名必须是英文、数字或下划线组成');
    return Promise.resolve();
  };

  const validatePassword = (rule, value) => {
    if (!value) return Promise.reject('密码必须输入');
    if (value.length < 4) return Promise.reject('密码长度不能小于4位');
    if (value.length > 12) return Promise.reject('密码长度不能大于12位');
    if (!/^[a-zA-Z0-9_]+$/.test(value))
      return Promise.reject('密码必须是英文、数字或下划线组成');
    return Promise.resolve();
  };

  const onFinish = async (values) => {
    try {
      const result = await reqLogin(values.username, values.password);
      if (result.status === 0) {
        message.success('登录成功');
        const userData = result.data;
        memoryUtils.user = userData;
        storageUtils.saveUser(userData);

        console.log('登录成功，内存用户状态：', memoryUtils.user);
        console.log('登录成功，本地存储用户状态：', storageUtils.getUser());

        navigate('/admin', { replace: true });
      } else {
        message.error(result.msg);
      }
    } catch (error) {
      message.error(`登录失败：${error.message}`);
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log('登录失败:', errorInfo);
  };

  return (
    <div className="login">
      <header className="login-header">
        <img src={logo} alt="logo" />
        <h1>React项目: 后台管理系统</h1>
      </header>
      <section className="login-content">
        <h2>用户登录</h2>
        <Form
          name="login-form"
          layout="vertical"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          initialValues={{ remember: true }}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, validator: validateUsername }]}
          >
            <Input
              prefix={<UserOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="请输入用户名"
            />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, validator: validatePassword }]}
          >
            <Input.Password
              prefix={<LockOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="请输入密码"
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </section>
    </div>
  );
};

export default Login;